<!-- 用户管理 -->
<template>
  <div class="app-container">
    <el-row :gutter="24">
      <!-- 用户列表 -->
      <el-col :lg="24" :xs="24">
        <!-- 搜索区域 -->
        <div class="search-container">
          <el-form
            ref="queryFormRef"
            :model="queryParams"
            :inline="true"
            label-width="auto"
          >
            <el-form-item :label="$t('Auth_Group')" prop="group_id">
              <el-select
                v-model="queryParams.group_id"
                :placeholder="$t('All')"
                clearable
                style="width: 100px"
              >
                <el-option :label="$t('All')" value="" />
                <el-option
                  v-for="item in groupOptions"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id ?? ''"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('Keyword')" prop="keywords">
              <el-input
                v-model="queryParams.keywords"
                :placeholder="$t('Please_Enter') + $t('Keyword')"
                clearable
              />
            </el-form-item>

            <el-form-item :label="$t('Status')" prop="status">
              <el-select
                v-model="queryParams.status"
                :placeholder="$t('All')"
                clearable
                style="width: 100px"
              >
                <el-option :label="$t('Normal')" :value="1" />
                <el-option :label="$t('Disable')" :value="2" />
              </el-select>
            </el-form-item>

            <el-form-item :label="$t('Create_Time')">
              <el-date-picker
                v-model="queryParams.createTime"
                :editable="false"
                type="daterange"
                range-separator="~"
                :start-placeholder="$t('Start_Time')"
                :end-placeholder="$t('End_Time')"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>

            <el-form-item class="search-buttons">
              <el-button type="primary" icon="search" @click="handleQuery">
                {{ $t("Search") }}
              </el-button>
              <el-button icon="refresh" @click="handleResetQuery">
                {{ $t("Reset") }}
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="hover" class="data-table">
          <div class="data-table__toolbar" style="margin-bottom: 10px">
            <div class="data-table__toolbar--actions">
              <el-button
                v-hasPerm="['authUserEdit']"
                type="success"
                icon="plus"
                @click="handleOpenDialog()"
              >
                {{ $t("Add") }}
              </el-button>
              <el-button
                v-hasPerm="'authUserDelBtn'"
                type="danger"
                icon="delete"
                :disabled="selectIds.length === 0"
                @click="handleDelete()"
              >
                {{ $t("Delete") }}
              </el-button>
            </div>
            <div class="data-table__toolbar--tools">
              <el-button
                v-hasPerm="'sys:user:import'"
                icon="upload"
                @click="handleOpenImportDialog"
              >
                导入
              </el-button>

              <el-button
                v-hasPerm="'sys:user:export'"
                icon="download"
                @click="handleExport"
              >
                导出
              </el-button>
            </div>
          </div>

          <el-table
            v-loading="loading"
            :data="pageData"
            :selectable="selectable"
            border
            stripe
            highlight-current-row
            class="data-table__content"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
              :label="$t('User_Name')"
              prop="username"
              width="150"
            />
            <el-table-column :label="$t('Avatar')" align="center" width="100">
              <template #default="scope">
                <el-avatar :size="50" :src="scope.row.avatar" />
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('Real_Name')"
              align="center"
              prop="realname"
              width="150"
            />
            <el-table-column
              :label="$t('Auth_Group')"
              width="200"
              align="center"
              prop="group_name"
            />
            <el-table-column
              :label="$t('Status')"
              align="center"
              prop="status"
              width="100"
            >
              <template #default="scope">
                <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">
                  {{ scope.row.status == 1 ? $t("Normal") : $t("Disable") }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('Login_Num')"
              align="center"
              prop="login_num"
              width="120"
            />
            <el-table-column
              :label="$t('Login_IP')"
              align="center"
              prop="login_last_ip"
              width="200"
            />
            <el-table-column
              :label="$t('Login_Time')"
              align="center"
              prop="login_last_at"
              width="200"
            />
            <el-table-column
              :label="$t('Create_Time')"
              align="center"
              prop="created_at"
              width="200"
            />
            <el-table-column
              :label="$t('Update_Time')"
              align="center"
              prop="updated_at"
              width="200"
            />
            <el-table-column
              :label="$t('Operate')"
              fixed="right"
              align="center"
            >
              <template #default="scope">
                <el-button
                  v-hasPerm="'authUserEdit'"
                  type="primary"
                  icon="edit"
                  link
                  size="small"
                  @click="handleOpenDialog(scope.row)"
                >
                  {{ $t("Edit") }}
                </el-button>
                <el-button
                  v-hasPerm="'authUserDelBtn'"
                  type="danger"
                  icon="delete"
                  link
                  size="small"
                  @click="handleDelete(scope.row.id)"
                >
                  {{ $t("Delete") }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            v-model:current-page="queryParams.page"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[15, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleQuery"
            @current-change="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="1000"
      :before-close="handleCloseDialog"
      :align-center="true"
      :close-on-click-modal="false"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="130px"
      >
        <el-form-item :label="$t('User_Name')" prop="username">
          <el-input
            v-model="formData.username"
            :readonly="!!formData.id"
            :placeholder="$t('User_Name')"
          />
        </el-form-item>
        <el-form-item :label="$t('Password')" prop="password">
          <el-input v-model="formData.password" :placeholder="$t('Password')" />
        </el-form-item>
        <el-form-item :label="$t('Real_Name')" prop="realname">
          <el-input
            v-model="formData.realname"
            :placeholder="$t('Real_Name')"
          />
        </el-form-item>
        <el-form-item :label="$t('Avatar')" prop="avatar">
          <SingleImageUpload v-model="formData.avatar" />
        </el-form-item>
        <el-form-item :label="$t('Auth_Group')" prop="group_id">
          <el-select
            v-model="formData.group_id"
            :placeholder="$t('Auth_Group')"
          >
            <el-option
              v-for="item in groupOptions"
              :key="item.id"
              :label="item.title"
              :value="item.id ?? ''"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('Status')" prop="status">
          <el-switch
            v-model="formData.status"
            inline-prompt
            :active-text="$t('Normal')"
            :inactive-text="$t('Disable')"
            :active-value="1"
            :inactive-value="2"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">
            {{ $t("Confirm") }}
          </el-button>
          <el-button @click="handleCloseDialog">{{ $t("Cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 用户导入 -->
    <UserImport v-model="importDialogVisible" @import-success="handleQuery()" />
  </div>
</template>

<script setup lang="ts">
import SingleImageUpload from "@/components/Upload/SingleImageUpload.vue";
import { useAppStore } from "@/store/modules/app";
import { DeviceEnum } from "@/enums/DeviceEnum";
import i18n from "@/lang/index";

import GroupAPI, { GroupListVO, GroupList } from "@/api/system/group.api";
import UserAPI, {
  UserForm,
  UserListVO,
  UserPageQuery,
  UserList,
} from "@/api/system/user.api";

import UserImport from "./components/UserImport.vue";

defineOptions({
  name: "User",
  inheritAttrs: false,
});

const appStore = useAppStore();

const queryFormRef = ref();
const userFormRef = ref();

const queryParams = reactive<UserPageQuery>({
  page: 1,
  pageSize: 15,
});
const selectable = (row: UserForm) => ![1].includes(Number(row.id));
const pageData = ref<UserList[]>();
const total = ref(0);
const loading = ref(false);

const dialog = reactive({
  visible: false,
  title: i18n.global.t("Add") + i18n.global.t("User"),
});
const drawerSize = computed(() =>
  appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"
);

let formData = reactive<UserForm>({
  id: "",
  username: "",
  password: "",
  realname: "",
  avatar: "",
  group_id: "",
  status: 1,
});

const rules = reactive({
  username: [
    {
      required: true,
      message: i18n.global.t("User_Name") + i18n.global.t("Not_Empty"),
      trigger: "blur",
    },
  ],
  realname: [
    {
      required: true,
      message: i18n.global.t("Real_Name") + i18n.global.t("Not_Empty"),
      trigger: "blur",
    },
  ],
  group_id: [
    {
      required: true,
      message: i18n.global.t("Auth_Group") + i18n.global.t("Not_Empty"),
      trigger: "blur",
    },
  ],
});

// 选中的用户ID
const selectIds = ref<number[]>([]);
// 角色下拉数据源
const groupOptions = ref<GroupList[]>();
// 导入弹窗显示状态
const importDialogVisible = ref(false);

// 查询
async function handleQuery() {
  loading.value = true;
  UserAPI.getPage(queryParams)
    .then((data: UserListVO) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 初始化查询参数
async function initParams() {
  GroupAPI.getPage({ page: 1, pageSize: 1000 })
    .then((data: GroupListVO) => {
      groupOptions.value = data.list;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.page = 1;
  queryParams.group_id = "";
  queryParams.status = "";
  queryParams.keywords = "";
  queryParams.createTime = undefined;
  handleQuery();
}

// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
async function handleOpenDialog(user?: UserForm) {
  dialog.visible = true;
  if (user?.id) {
    dialog.title = i18n.global.t("Edit") + i18n.global.t("User");
    //复制 user 给formData.value
    Object.assign(formData, user);
  } else {
    dialog.title = i18n.global.t("Add") + i18n.global.t("User");
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  formData.id = "";
  formData.username = "";
  formData.password = "";
  formData.group_id = "";
  formData.realname = "";
  formData.status = 1;
}

// 提交用户表单（防抖）
const handleSubmit = useDebounceFn(() => {
  userFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      if (userId) {
        UserAPI.update(formData)
          .then(() => {
            ElMessage.success(i18n.global.t("Operate_Success"));
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        UserAPI.create(formData)
          .then(() => {
            ElMessage.success(i18n.global.t("Operate_Success"));
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 1000);

/**
 * 删除用户
 *
 * @param id  用户ID
 */
function handleDelete(id?: number) {
  const userIds = [id || selectIds.value].join(",");
  if (!userIds) {
    ElMessage.warning(i18n.global.t("Please_Select_Delete_Item"));
    return;
  }

  ElMessageBox.confirm(
    i18n.global.t("Confirm_Delete"),
    i18n.global.t("Warning"),
    {
      confirmButtonText: i18n.global.t("Confirm"),
      cancelButtonText: i18n.global.t("Cancel"),
      type: "warning",
    }
  ).then(
    function () {
      loading.value = true;
      console.log(userIds);
      UserAPI.deleteByIds({ ids: userIds })
        .then(() => {
          ElMessage.success(i18n.global.t("Operate_Success"));
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info(i18n.global.t("Operate_Cancel"));
    }
  );
}

// 打开导入弹窗
function handleOpenImportDialog() {
  importDialogVisible.value = true;
}

// 导出用户
function handleExport() {
  // UserAPI.export(queryParams).then((response: any) => {
  //   const fileData = response.data;
  //   const fileName = decodeURI(
  //     response.headers["content-disposition"].split(";")[1].split("=")[1]
  //   );
  //   const fileType =
  //     "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";
  //   const blob = new Blob([fileData], { type: fileType });
  //   const downloadUrl = window.URL.createObjectURL(blob);
  //   const downloadLink = document.createElement("a");
  //   downloadLink.href = downloadUrl;
  //   downloadLink.download = fileName;
  //   document.body.appendChild(downloadLink);
  //   downloadLink.click();
  //   document.body.removeChild(downloadLink);
  //   window.URL.revokeObjectURL(downloadUrl);
  // });
}

onMounted(() => {
  initParams();
  handleQuery();
});
</script>
